import React, { useState, useEffect, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import {
  Layout,
  Menu,
  Progress,
  Button,
  Input,
  List,
  Card,
  Space,
  Drawer,
  message,
  Select,
  Tooltip,
  Tag,
  Timeline,
  Tabs,
  Row,
  Col,
  Statistic,
  Empty,
  Spin
} from 'antd';
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  StepForwardOutlined,
  StepBackwardOutlined,
  FullscreenOutlined,
  FileTextOutlined,
  BookOutlined,
  EditOutlined,
  SaveOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  HistoryOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  HighlightOutlined,
  DeleteOutlined,
  PushpinOutlined,
  RightOutlined
} from '@ant-design/icons';
import VideoJS from 'video.js';
import 'video.js/dist/video-js.css';
import {
  updateLearningProgress,
  markChapterComplete,
  calculateAndUpdateCourseProgress,
  saveNote,
  deleteNote
} from '../../store/learningSlice';
import { mockCourses } from '../../api/mockData';

const { Sider, Content } = Layout;
const { TabPane } = Tabs;
const { TextArea } = Input;
const { Option } = Select;

const LearningPage = () => {
  const videoRef = useRef(null);
  const playerRef = useRef(null);
  const menuRef = useRef(null);
  const containerRef = useRef(null);
  const location = useLocation();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { courseId, chapterId } = useParams();

  // 从 Redux 获取当前课程信息
  const currentCourse = useSelector(state => state.course.currentCourse);
  const learningProgress = useSelector(state => state.learning.progress[courseId] || {});
  const notes = useSelector(state => state.learning.notes[chapterId] || []);
  const chapter = useSelector(state =>
    state.course.currentCourse?.chapters?.find(c => c.id === chapterId)
  );

  // 状态管理
  const [currentChapter, setCurrentChapter] = useState(null);
  const [currentLesson, setCurrentLesson] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [playbackRate, setPlaybackRate] = useState(1);
  const [showNotes, setShowNotes] = useState(false);
  const [noteContent, setNoteContent] = useState('');
  const [selectedSubtitle, setSelectedSubtitle] = useState('cn');
  const [collapsed, setCollapsed] = useState(false);
  const [showProgressDrawer, setShowProgressDrawer] = useState(false);
  const [lastPosition, setLastPosition] = useState(0);
  const [currentNote, setCurrentNote] = useState('');
  const [selectedText, setSelectedText] = useState('');
  const [showNoteDrawer, setShowNoteDrawer] = useState(false);
  const [subtitles, setSubtitles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [courses, setCourses] = useState([]);

  // 从 Redux 获取用户和学习进度数据
  const userId = useSelector(state => state.user.currentUser?.id);
  const courseProgress = useSelector(state => state.learning.courseProgress || {});

  // 获取已报名课程数据
  useEffect(() => {
    const fetchCourses = async () => {
      try {
        setLoading(true);
        // 模拟 API 调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        const coursesData = mockCourses || [];
        setCourses(coursesData);
      } catch (error) {
        console.error('获取课程失败:', error);
        message.error('加载课程失败，请刷新重试');
      } finally {
        setLoading(false);
      }
    };

    fetchCourses();
  }, []);

  // 初始化视频播放器
  useEffect(() => {
    if (videoRef.current && chapter?.type === 'video') {
      const options = {
        controls: true,
        fluid: true,
        playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2],
        controlBar: {
          children: [
            'playToggle',
            'volumePanel',
            'currentTimeDisplay',
            'timeDivider',
            'durationDisplay',
            'progressControl',
            'playbackRateMenuButton',
            'subtitlesButton',
            'fullscreenToggle',
          ]
        }
      };

      // 如果有字幕，添加字幕轨道
      if (chapter.subtitles) {
        setSubtitles(chapter.subtitles);
        options.tracks = chapter.subtitles.map(sub => ({
          kind: 'subtitles',
          src: sub.url,
          srclang: sub.lang,
          label: sub.label
        }));
      }

      playerRef.current = VideoJS(videoRef.current, options);

      // 恢复上次播放位置
      if (learningProgress[chapter.id]?.videoPosition) {
        playerRef.current.currentTime(learningProgress[chapter.id].videoPosition);
      }

      // 监听播放进度
      playerRef.current.on('timeupdate', () => {
        const time = playerRef.current.currentTime();
        setCurrentTime(time);
        // 每30秒保存一次进度
        if (Math.abs(time - (learningProgress[chapter.id]?.videoPosition || 0)) >= 30) {
          handleSaveProgress(time);
        }
      });

      playerRef.current.on('loadedmetadata', () => {
        setDuration(playerRef.current.duration());
      });

      // 监听视频完成
      playerRef.current.on('ended', () => {
        handleChapterComplete(chapter.id);
      });

      return () => {
        if (playerRef.current) {
          playerRef.current.dispose();
        }
      };
    }
  }, [chapter]);

  // 更新进度保存逻辑
  const handleSaveProgress = async (time) => {
    try {
      const isCompleted = time >= playerRef.current.duration() - 5; // 视频剩余5秒内视为完成
      await dispatch(updateLearningProgress({
        courseId,
        chapterId,
        progress: {
          videoPosition: time,
          completed: isCompleted,
          lastUpdated: new Date().toISOString()
        }
      }));

      if (isCompleted && !learningProgress[chapter.id]?.completed) {
        message.success('恭喜完成本章节学习！');
        // 更新课程总进度
        dispatch(calculateAndUpdateCourseProgress(courseId));
      }
    } catch (error) {
      message.error('保存进度失败');
    }
  };

  // 自动保存进度的间隔
  useEffect(() => {
    let saveInterval;
    if (playerRef.current) {
      saveInterval = setInterval(() => {
        const currentTime = playerRef.current.currentTime();
        if (currentTime > 0) {
          handleSaveProgress(currentTime);
        }
      }, 30000); // 每30秒保存一次进度
    }

    return () => {
      if (saveInterval) {
        clearInterval(saveInterval);
      }
    };
  }, [playerRef.current]);

  // 离开页面时保存进度
  useEffect(() => {
    return () => {
      if (playerRef.current) {
        handleSaveProgress(playerRef.current.currentTime());
      }
    };
  }, []);

  // 处理章节完成
  const handleChapterComplete = async (chapterId) => {
    try {
      await dispatch(markChapterComplete({
        courseId,
        chapterId,
        completedAt: new Date().toISOString()
      }));
      message.success('章节完成！');
    } catch (error) {
      message.error('更新进度失败');
    }
  };

  // 计算课程总进度
  const calculateCourseProgress = () => {
    if (!currentCourse?.chapters) return 0;
    const completedChapters = currentCourse.chapters.filter(
      chapter => learningProgress[chapter.id]?.completed
    ).length;
    return Math.round((completedChapters / currentCourse.chapters.length) * 100);
  };

  // 切换章节
  const handleChapterChange = (chapter) => {
    // 保存当前章节进度
    if (currentChapter && playerRef.current) {
      handleSaveProgress(playerRef.current.currentTime());
    }

    setCurrentChapter(chapter);
    if (playerRef.current) {
      playerRef.current.src({ type: 'video/mp4', src: chapter.videoUrl });
      // 恢复该章节的播放进度
      const savedProgress = learningProgress[chapter.id];
      if (savedProgress?.videoPosition) {
        playerRef.current.currentTime(savedProgress.videoPosition);
      }
    }
  };

  // 视频控制功能
  const videoControls = {
    togglePlay: () => {
      if (playerRef.current) {
        if (isPlaying) {
          playerRef.current.pause();
        } else {
          playerRef.current.play();
        }
        setIsPlaying(!isPlaying);
      }
    },
    seek: (time) => {
      if (playerRef.current) {
        playerRef.current.currentTime(playerRef.current.currentTime() + time);
      }
    },
    setPlaybackRate: (rate) => {
      if (playerRef.current) {
        playerRef.current.playbackRate(rate);
        setPlaybackRate(rate);
      }
    },
    toggleFullscreen: () => {
      if (playerRef.current) {
        if (playerRef.current.isFullscreen()) {
          playerRef.current.exitFullscreen();
        } else {
          playerRef.current.requestFullscreen();
        }
      }
    }
  };

  // 保存笔记
  const handleSaveNote = async () => {
    if (!currentNote.trim()) {
      message.warning('笔记内容不能为空');
      return;
    }

    try {
      await dispatch(saveNote({
        chapterId,
        note: {
          id: Date.now(),
          content: currentNote,
          timestamp: currentTime,
          selectedText,
          createdAt: new Date().toISOString()
        }
      }));
      setCurrentNote('');
      setSelectedText('');
      message.success('笔记保存成功');
    } catch (error) {
      message.error('保存笔记失败');
    }
  };

  // 删除笔记
  const handleDeleteNote = async (noteId) => {
    try {
      await dispatch(deleteNote({
        chapterId,
        noteId
      }));
      message.success('笔记已删除');
    } catch (error) {
      message.error('删除笔记失败');
    }
  };

  // 处理文本选择（用于文字课程）
  const handleTextSelection = () => {
    const selection = window.getSelection();
    const text = selection.toString().trim();
    if (text) {
      setSelectedText(text);
      setShowNoteDrawer(true);
    }
  };

  // 渲染学习进度抽屉
  const renderProgressDrawer = () => (
    <Drawer
      title="学习进度详情"
      placement="right"
      onClose={() => setShowProgressDrawer(false)}
      visible={showProgressDrawer}
      width={400}
      getContainer={false}
    >
      <Card>
        <Tooltip title="课程总进度" getPopupContainer={() => containerRef.current}>
          <Progress
            type="circle"
            percent={calculateCourseProgress()}
            format={percent => `${percent}% 完成`}
          />
        </Tooltip>
        <div style={{ marginTop: 16 }}>
          <p>总学习时长: {calculateTotalLearningTime()}</p>
          <p>已完成章节: {getCompletedChaptersCount()}/{currentCourse?.chapters?.length}</p>
        </div>
      </Card>

      <Timeline style={{ marginTop: 24 }}>
        {currentCourse?.chapters?.map(chapter => {
          const progress = learningProgress[chapter.id] || {};
          return (
            <Timeline.Item
              key={chapter.id}
              dot={progress.completed ? <CheckCircleOutlined style={{ color: '#52c41a' }} /> : <ClockCircleOutlined />}
            >
              <div>
                <strong>{chapter.title}</strong>
                {progress.completed ? (
                  <Tag color="success" style={{ marginLeft: 8 }}>已完成</Tag>
                ) : progress.videoPosition ? (
                  <Tag color="processing" style={{ marginLeft: 8 }}>
                    进行中 ({Math.round((progress.videoPosition / chapter.duration) * 100)}%)
                  </Tag>
                ) : (
                  <Tag style={{ marginLeft: 8 }}>未开始</Tag>
                )}
                {progress.lastUpdated && (
                  <div style={{ fontSize: 12, color: '#999' }}>
                    上次学习: {new Date(progress.lastUpdated).toLocaleString()}
                  </div>
                )}
              </div>
            </Timeline.Item>
          );
        })}
      </Timeline>
    </Drawer>
  );

  // 计算总学习时长
  const calculateTotalLearningTime = () => {
    if (!currentCourse?.chapters) return '0分钟';
    const totalSeconds = Object.values(learningProgress).reduce((total, progress) => {
      return total + (progress.videoPosition || 0);
    }, 0);
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    return hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`;
  };

  // 获取已完成章节数
  const getCompletedChaptersCount = () => {
    return currentCourse?.chapters?.filter(chapter =>
      learningProgress[chapter.id]?.completed
    ).length || 0;
  };

  // 渲染视频课程
  const renderVideoContent = () => (
    <div>
      <video
        ref={videoRef}
        className="video-js vjs-big-play-centered"
        style={{ width: '100%', maxHeight: '70vh' }}
      />
      {subtitles.length > 0 && (
        <Select
          style={{ width: 200, marginTop: 16 }}
          value={selectedSubtitle}
          onChange={setSelectedSubtitle}
          placeholder="选择字幕"
        >
          <Select.Option value="">关闭字幕</Select.Option>
          {subtitles.map(sub => (
            <Select.Option key={sub.lang} value={sub.lang}>
              {sub.label}
            </Select.Option>
          ))}
        </Select>
      )}
    </div>
  );

  // 渲染文字课程
  const renderTextContent = () => (
    <Card
      className="text-content"
      style={{ maxHeight: '70vh', overflow: 'auto' }}
      onMouseUp={handleTextSelection}
    >
      <div dangerouslySetInnerHTML={{ __html: chapter?.content }} />
    </Card>
  );

  // 渲染笔记列表
  const renderNotes = () => (
    <List
      dataSource={notes}
      renderItem={note => (
        <List.Item
          actions={[
            <Button
              icon={<DeleteOutlined />}
              onClick={() => handleDeleteNote(note.id)}
              type="text"
              danger
            />
          ]}
        >
          <List.Item.Meta
            title={
              <Space>
                {note.timestamp && (
                  <Tag color="blue">
                    {new Date(note.timestamp * 1000).toISOString().substr(11, 8)}
                  </Tag>
                )}
                {note.selectedText && (
                  <Tag color="purple" icon={<HighlightOutlined />}>
                    已标记文本
                  </Tag>
                )}
              </Space>
            }
            description={note.content}
          />
        </List.Item>
      )}
    />
  );

  // 渲染笔记抽屉
  const renderNoteDrawer = () => (
    <Drawer
      title="添加笔记"
      placement="right"
      width={400}
      onClose={() => setShowNoteDrawer(false)}
      visible={showNoteDrawer}
      extra={
        <Button type="primary" icon={<SaveOutlined />} onClick={handleSaveNote}>
          保存笔记
        </Button>
      }
    >
      {selectedText && (
        <Card size="small" style={{ marginBottom: 16 }}>
          <p>已选择文本：</p>
          <p style={{ color: '#1890ff' }}>{selectedText}</p>
        </Card>
      )}
      <TextArea
        rows={6}
        value={currentNote}
        onChange={e => setCurrentNote(e.target.value)}
        placeholder="输入笔记内容..."
      />
      <div style={{ marginTop: 16 }}>
        <h4>章节笔记</h4>
        {renderNotes()}
      </div>
    </Drawer>
  );

  // 格式化学习时长
  const formatLearningTime = (seconds) => {
    if (!seconds) return '0分钟';
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`;
  };

  // 获取最近学习的章节
  const getLastLearningChapter = (course) => {
    if (!course?.chapters?.length) return null;

    const progress = learningProgress[course.id] || {};
    return course.chapters.find(ch =>
      progress[ch.id]?.videoPosition && !progress[ch.id]?.completed
    ) || course.chapters[0];
  };

  // 渲染课程卡片
  const renderCourseCard = (course) => {
    if (!course?.chapters?.length) return null;

    const progress = courseProgress[course.id] || {};
    const completedChapters = course.chapters.filter(
      ch => learningProgress[course.id]?.[ch.id]?.completed
    ).length;

    return (
      <Card
        key={course.id}
        hoverable
        style={{ marginBottom: 16 }}
      >
        <Card.Meta
          title={
            <Space>
              {course.title}
              <Progress
                percent={Math.round((completedChapters / course.chapters.length) * 100)}
                size="small"
                style={{ width: 100 }}
              />
            </Space>
          }
          description={
            <Row gutter={[16, 16]}>
              <Col span={8}>
                <Statistic
                  title="学习时长"
                  value={formatLearningTime(progress.totalTime || 0)}
                  prefix={<ClockCircleOutlined />}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="已完成章节"
                  value={`${completedChapters}/${course.chapters.length}`}
                  prefix={<CheckCircleOutlined />}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="总章节"
                  value={course.chapters.length}
                  prefix={<BookOutlined />}
                />
              </Col>
            </Row>
          }
        />

        <List
          style={{ marginTop: 16 }}
          size="small"
          dataSource={course.chapters.slice(0, 3)}
          renderItem={chapter => {
            const chapterProgress = learningProgress[course.id]?.[chapter.id] || {};
            return (
              <List.Item
                actions={[
                  <Button
                    type="link"
                    size="small"
                    onClick={() => navigate(`/learning/${course.id}/${chapter.id}`)}
                  >
                    {chapterProgress.completed ? '复习' : '继续学习'}
                  </Button>
                ]}
              >
                <List.Item.Meta
                  avatar={chapter.type === 'video' ? <PlayCircleOutlined /> : <FileTextOutlined />}
                  title={
                    <Space>
                      {chapter.title}
                      {chapterProgress.completed ? (
                        <Tag color="success">已完成</Tag>
                      ) : chapterProgress.videoPosition ? (
                        <Tag color="processing">进行中</Tag>
                      ) : (
                        <Tag>未开始</Tag>
                      )}
                    </Space>
                  }
                  description={
                    chapter.type === 'video' && chapterProgress.videoPosition && (
                      <Progress
                        percent={Math.round((chapterProgress.videoPosition / chapter.duration) * 100)}
                        size="small"
                        status={chapterProgress.completed ? "success" : "active"}
                      />
                    )
                  }
                />
              </List.Item>
            );
          }}
        />

        {course.chapters.length > 3 && (
          <Button
            type="link"
            block
            onClick={() => navigate(`/courses/${course.id}`)}
          >
            查看全部章节 ({course.chapters.length})
          </Button>
        )}
      </Card>
    );
  };

  // Modify the menu rendering to include null checks
  const renderMenu = () => (
    <Menu
      ref={menuRef}
      mode="inline"
      selectedKeys={[chapterId]}
      style={{ height: 'calc(100vh - 64px)', overflowY: 'auto' }}
    >
      {Array.isArray(courses) && courses.map(course => {
        if (!course) return null;
        const progress = courseProgress[course.id] || {};
        const lastChapter = getLastLearningChapter(course);
        return (
          <Menu.Item
            key={course.id}
            icon={progress.completedChapters === (course.chapters?.length || 0) ? <CheckCircleOutlined /> : <PlayCircleOutlined />}
            onClick={() => lastChapter && navigate(`/learning/${course.id}/${lastChapter.id}`)}
          >
            <Space>
              {course.title}
              {!collapsed && progress.completedChapters && progress.completedChapters === (course.chapters?.length || 0) && (
                <Tag color="success" style={{ marginLeft: 8 }}>已完成</Tag>
              )}
            </Space>
          </Menu.Item>
        );
      })}
    </Menu>
  );

  return (
    <Layout style={{ height: '100vh' }} ref={containerRef}>
      <Sider
        width={300}
        collapsible
        collapsed={collapsed}
        onCollapse={setCollapsed}
        trigger={null}
      >
        <div style={{ padding: '16px' }}>
          <Space>
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed(!collapsed)}
            />
            <Progress
              percent={calculateCourseProgress()}
              size="small"
              style={{ width: collapsed ? 0 : 150 }}
            />
          </Space>
        </div>
        {renderMenu()}
      </Sider>

      <Content style={{ padding: 24 }}>
        <Space style={{ marginBottom: 16 }}>
          <Button
            icon={<HistoryOutlined />}
            onClick={() => setShowProgressDrawer(true)}
          >
            学习进度
          </Button>
        </Space>

        <Card
          title={chapter?.title}
          extra={
            <Space>
              <Button
                icon={<HighlightOutlined />}
                onClick={() => setShowNoteDrawer(true)}
              >
                笔记
              </Button>
            </Space>
          }
        >
          {chapter?.type === 'video' ? renderVideoContent() : renderTextContent()}
        </Card>

        {renderProgressDrawer()}
        {renderNoteDrawer()}

        <Card>
          {loading ? (
            <div style={{ textAlign: 'center', padding: '50px 0' }}>
              <Spin size="large" />
            </div>
          ) : Array.isArray(courses) && courses.length > 0 ? (
            courses.map(course => course && renderCourseCard(course))
          ) : (
            <Empty
              description="暂无课程数据"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            >
              <Button
                type="primary"
                onClick={() => navigate('/courses')}
              >
                去选课
              </Button>
            </Empty>
          )}
        </Card>
      </Content>
    </Layout>
  );
};

export default LearningPage; 